const express = require('express')

const app = express()

app.use(require('cors')()) // 设置允许跨域
app.use(express.json()) // 让express可以识别创建前端发来的json

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/vuenode')

const Schema = mongoose.Schema // 拿到Schema对象，可以用来设计表结构

// 设计表结构（文档）
const schemaModel = new Schema({
  title: {
    type: String
  },
  body: {
    type: String
  }
})

// 将表结构（文档）发布为模型（document）
const ArticleModel = mongoose.model('Article', schemaModel)


app.get('/', (req, res) => {
  res.send('hello world')
})

app.post('/api/articles', (req, res) => {
  const article = ArticleModel.create(req.body)
  res.send(article)
})

app.get('/api/articles', (req, res) => {
  ArticleModel.find(function(err, data) {
    res.send(data)
  })
})
app.listen(3000, () => {
  console.log('server is running...');
})